﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography;

namespace FishServe.Core
{
    public class ReleaseManifestReader
    {
        private static readonly byte[] _signingCertificateBytes = { 
            0x30, 0x82, 0x02, 0x31, 0x30, 0x82, 0x01, 0x9A, 0xA0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x10, 0xD6, 0xDE, 0xAC, 0x6F, 0xAF, 
            0x63, 0x3B, 0xA0, 0x4F, 0x18, 0xC6, 0x2C, 0x19, 0xE8, 0x84, 0xD8, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 
            0x0D, 0x01, 0x01, 0x05, 0x05, 0x00, 0x30, 0x57, 0x31, 0x55, 0x30, 0x53, 0x06, 0x03, 0x55, 0x04, 0x03, 0x1E, 0x4C, 0x00, 
            0x7B, 0x00, 0x39, 0x00, 0x36, 0x00, 0x41, 0x00, 0x38, 0x00, 0x33, 0x00, 0x34, 0x00, 0x43, 0x00, 0x32, 0x00, 0x2D, 0x00, 
            0x38, 0x00, 0x34, 0x00, 0x38, 0x00, 0x38, 0x00, 0x2D, 0x00, 0x34, 0x00, 0x46, 0x00, 0x43, 0x00, 0x45, 0x00, 0x2D, 0x00, 
            0x38, 0x00, 0x30, 0x00, 0x42, 0x00, 0x32, 0x00, 0x2D, 0x00, 0x38, 0x00, 0x44, 0x00, 0x45, 0x00, 0x38, 0x00, 0x43, 0x00, 
            0x33, 0x00, 0x42, 0x00, 0x44, 0x00, 0x46, 0x00, 0x35, 0x00, 0x42, 0x00, 0x37, 0x00, 0x7D, 0x30, 0x1E, 0x17, 0x0D, 0x30, 
            0x38, 0x31, 0x32, 0x32, 0x38, 0x30, 0x38, 0x34, 0x37, 0x34, 0x39, 0x5A, 0x17, 0x0D, 0x30, 0x39, 0x31, 0x32, 0x32, 0x38, 
            0x31, 0x34, 0x34, 0x37, 0x34, 0x39, 0x5A, 0x30, 0x57, 0x31, 0x55, 0x30, 0x53, 0x06, 0x03, 0x55, 0x04, 0x03, 0x1E, 0x4C, 
            0x00, 0x7B, 0x00, 0x39, 0x00, 0x36, 0x00, 0x41, 0x00, 0x38, 0x00, 0x33, 0x00, 0x34, 0x00, 0x43, 0x00, 0x32, 0x00, 0x2D, 
            0x00, 0x38, 0x00, 0x34, 0x00, 0x38, 0x00, 0x38, 0x00, 0x2D, 0x00, 0x34, 0x00, 0x46, 0x00, 0x43, 0x00, 0x45, 0x00, 0x2D, 
            0x00, 0x38, 0x00, 0x30, 0x00, 0x42, 0x00, 0x32, 0x00, 0x2D, 0x00, 0x38, 0x00, 0x44, 0x00, 0x45, 0x00, 0x38, 0x00, 0x43, 
            0x00, 0x33, 0x00, 0x42, 0x00, 0x44, 0x00, 0x46, 0x00, 0x35, 0x00, 0x42, 0x00, 0x37, 0x00, 0x7D, 0x30, 0x81, 0x9F, 0x30, 
            0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x81, 0x8D, 0x00, 0x30, 0x81, 
            0x89, 0x02, 0x81, 0x81, 0x00, 0xBF, 0x4F, 0x44, 0xF0, 0x6D, 0x6E, 0x7D, 0xF9, 0x6E, 0x1E, 0x76, 0x5B, 0xA9, 0x18, 0x98, 
            0xCD, 0x8A, 0xA1, 0x13, 0x8C, 0x25, 0xAB, 0xC1, 0xAD, 0x24, 0x31, 0xD5, 0x4A, 0xAD, 0x65, 0x5B, 0x42, 0x7F, 0x2E, 0x6B, 
            0x4A, 0xE0, 0x12, 0x83, 0xE7, 0x27, 0xD1, 0x20, 0x1D, 0x8F, 0x8F, 0x1E, 0xC1, 0xFB, 0x16, 0xFD, 0x19, 0x42, 0xBB, 0xE7, 
            0xAD, 0x2F, 0xAE, 0x05, 0xC9, 0x93, 0xF5, 0xE3, 0x5B, 0xDE, 0x3C, 0x73, 0x52, 0x8C, 0x5A, 0x42, 0xDC, 0xD8, 0x0C, 0x4A, 
            0xE5, 0x18, 0xA0, 0xFD, 0x61, 0x30, 0x87, 0x53, 0xEB, 0x6A, 0xF3, 0x18, 0xCC, 0x29, 0x7C, 0x23, 0xCD, 0x2E, 0x5C, 0xD5, 
            0x09, 0xB4, 0x71, 0x39, 0x34, 0x15, 0xA2, 0x16, 0x02, 0x0D, 0xEE, 0x64, 0x6A, 0x14, 0x71, 0xBF, 0xC3, 0xC8, 0x3B, 0xB6, 
            0x0F, 0x48, 0x8C, 0x73, 0x3E, 0xBC, 0xEC, 0xA3, 0xCD, 0x7D, 0x68, 0xBE, 0x1D, 0x02, 0x03, 0x01, 0x00, 0x01, 0x30, 0x0D, 
            0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x05, 0x05, 0x00, 0x03, 0x81, 0x81, 0x00, 0x31, 0xE8, 0x0F, 
            0xF2, 0x05, 0x55, 0x89, 0x18, 0xDB, 0x59, 0x57, 0x8D, 0x48, 0x0D, 0x26, 0x35, 0xD5, 0x71, 0xEC, 0x8D, 0xE4, 0x13, 0xBB, 
            0x5F, 0xF1, 0x6C, 0x0F, 0x98, 0xE9, 0x72, 0xE1, 0x71, 0x88, 0xB3, 0x59, 0x5B, 0xB0, 0x6D, 0x58, 0xD6, 0xEA, 0x3F, 0x29, 
            0xA3, 0x0D, 0x0C, 0xCB, 0x99, 0x6E, 0x7C, 0x34, 0xD6, 0x2F, 0xC5, 0xA0, 0xC3, 0x9D, 0x2F, 0x56, 0x9A, 0xC5, 0x66, 0xAD, 
            0x63, 0xAB, 0xD8, 0xC1, 0x8B, 0xB6, 0x84, 0xCD, 0xEA, 0xEA, 0x46, 0xD6, 0x2D, 0x5F, 0x9C, 0x24, 0x89, 0xD1, 0xCC, 0xE4, 
            0x8F, 0xBB, 0xEA, 0x98, 0xA1, 0xDC, 0x76, 0x84, 0x2A, 0xC5, 0xBE, 0xE3, 0x78, 0xBB, 0x81, 0x59, 0x9D, 0x18, 0x97, 0x77, 
            0x91, 0x8F, 0x03, 0x38, 0x50, 0x31, 0x23, 0x95, 0xDF, 0x69, 0x8C, 0xDF, 0x16, 0x6B, 0x52, 0x6E, 0x47, 0x29, 0x6B, 0x11, 
            0xD6, 0x61, 0x90, 0x03, 0x51 };

        internal ReleaseManifestReader()
        {}

        public static ReleaseManifest Read(string manifestDir, string manifestFilename)
        {
            string manifestFullFilename = Path.Combine(manifestDir, manifestFilename);

            try
            {
                return ReadReleaseManifest(manifestFullFilename);
            }
            catch (Exception ex)
            {
                throw new Exception(String.Format("Failed to load manifest file '{0}'", manifestFullFilename), ex);
            }
        }

		/// <summary>
		/// Read a Non-Encrypted Manifest File.
		/// </summary>
		/// <param name="manifestFullFilename"></param>
		/// <returns></returns>
		public static ReleaseManifest ReadReleaseManifestXX(string manifestFullFilename)
		{
			if (!File.Exists(manifestFullFilename))
				throw new FileNotFoundException(String.Format("Manifest file '{0}' not found", manifestFullFilename));

			XDocument releaseManifestDoc = null;
			try
			{
				//XDocument.Load(manifestFullFilename);
				releaseManifestDoc = XDocument.Load(manifestFullFilename);
			}
			catch (Exception ex)
			{
				throw new Exception("Failed to parse encoded release manifest document", ex);
			}

			return new ReleaseManifest(manifestFullFilename, releaseManifestDoc.Root);
		}
        public static ReleaseManifest ReadReleaseManifest(string manifestFullFilename)
        {
            ReleaseManifest releaseManifest = null;

            if (!File.Exists(manifestFullFilename))
                throw new FileNotFoundException(String.Format("Manifest file '{0}' not found", manifestFullFilename));

            XDocument signedManifestDoc = null;
            try
            {
                signedManifestDoc = XDocument.Load(manifestFullFilename);
            }
            catch (Exception ex)
            {
                throw new Exception("Failed to load signed manifest document", ex);
            }

            XElement signedManifestElement = signedManifestDoc.Element("SignedReleaseManifest");
            if (signedManifestElement == null)
                throw new Exception("<SignedManifest> element not found");

            XElement encodedManifestElement = signedManifestElement.Element("EncodedManifest");
            if( encodedManifestElement == null )
                throw new Exception("<EncodedManifest> element missing");

            XElement encodedSignatureElement = signedManifestElement.Element("EncodedSignature");
            if (encodedSignatureElement == null)
                throw new Exception("<EncodedSignature> element missing");

            X509Certificate2 signingCertificate = new X509Certificate2(_signingCertificateBytes);
            RSACryptoServiceProvider publicKeyCsp = signingCertificate.PublicKey.Key as RSACryptoServiceProvider;

            byte[] releaseManifestBytes = Convert.FromBase64String(encodedManifestElement.Value);
            byte[] releaseManifestSignatureBytes = Convert.FromBase64String(encodedSignatureElement.Value);

            if (!publicKeyCsp.VerifyData(releaseManifestBytes, new SHA1CryptoServiceProvider(), releaseManifestSignatureBytes))
                throw new Exception("Signature verification failed");

            string releaseManifestString = UTF8Encoding.UTF8.GetString(releaseManifestBytes);

            XDocument releaseManifestDoc = null;
            try
            {
                releaseManifestDoc = XDocument.Parse(releaseManifestString);
            }
            catch (Exception ex)
            {
                throw new Exception("Failed to parse encoded release manifest document", ex);
            }

            releaseManifest = new ReleaseManifest(manifestFullFilename, releaseManifestDoc.Root);

            return releaseManifest;
        }        
    }
}
